package com.kbbywyclient.ui.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.app.API;
import com.kbbywyclient.data.entity.MyBusinessCon;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.MyBusinessConModule;
import com.kbbywyclient.presenter.MyBusinessConPresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.contarct.MyBusinessConContarct;
import com.kbbywyclient.util.CheckFormat;
import com.kbbywyclient.util.FileUtils;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomDialog;
import com.kbbywyclient.widget.CustomToolBar;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Description:
 * Created by FHW
 * on 2017/5/11
 */

public class MyBusinessConActivity extends BaseActivity implements MyBusinessConContarct.View {

    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;

    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_mobile)
    TextView tv_mobile;
    @BindView(R.id.tv_wechat)
    TextView tv_wechat;
    @BindView(R.id.iv_two_code)
    ImageView iv_two_code;
    @BindView(R.id.rl_qq)
    RelativeLayout rl_qq;

    @Inject
    MyBusinessConPresenter myBusinessConPresenter;
    private String qq = "";
    private String mobile = "";

    private CustomDialog dialog;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_business_con;
    }

    @OnClick({R.id.tv_qq, R.id.tv_mobile})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_qq:
                if (CheckFormat.checkApkExist(this, "com.tencent.mobileqq")) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=" + qq + "&version=1")));
                    setScreenAction("通信", "业务顾问-qq交谈");
                } else {
                    ToastUtil.showShort("本机未安装QQ应用");
                }
                break;
            case R.id.tv_mobile:
                showInfoDialog();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("我的业务顾问");
    }

    @Override
    protected void initView() {
        v_toolbar.setLeftViewOnClickLinster(v -> finish());
        iv_two_code.setOnLongClickListener(v->{
            Object tag=iv_two_code.getTag();
            if(tag!=null){
                String picAddress= (String) tag;
                if(!TextUtils.isEmpty(picAddress)){
                    //显示保存图片对话框
                    showSavePicDialog(picAddress);
                }
            }
            return true;
        });
    }

    @Override
    public void initData() {
        myBusinessConPresenter.getMyBusinessCon(PreUtils.getUser(this).getSalesID() + "");
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getMyBusinessConComponent(new MyBusinessConModule(this)).inject(this);
    }

    /**
     *
     */
    private void showInfoDialog() {
        dialog = new CustomDialog(this, R.style.Customdialog, "", mobile
                , new CustomDialog.ButtonListener() {
            @Override
            public void left() {
                dialog.dismiss();
            }

            @Override
            public void right() {
                ViewUtils.dialPhoneNumber(MyBusinessConActivity.this, mobile);
                setScreenAction("通信", "业务顾问-拨打电话");
                dialog.dismiss();
            }
        }, getString(R.string.cancel), "呼叫");
        dialog.show();
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    @Override
    public void loadSucBusinessCon(MyBusinessCon.MySalesBean mySales) {
        qq = mySales.getQQ();
        mobile = mySales.getPHONE();

        if (StringUtil.isNotEmpty(qq)) {
            rl_qq.setVisibility(View.VISIBLE);
        } else {
            rl_qq.setVisibility(View.GONE);
        }
        ViewUtils.setText(tv_name, mySales.getNAME());
        ViewUtils.setText(tv_mobile, mobile);
        ViewUtils.setText(tv_wechat, mySales.getWeiXinID());
        String picAddress=mySales.getWeiXinImage();
        if(!TextUtils.isEmpty(picAddress)){
            picAddress=API.PIC_ADDRESS + mySales.getWeiXinImage();
            iv_two_code.setTag(picAddress);
            Picasso.with(MyBusinessConActivity.this).
                    load(picAddress).
                    resize(180, 180).
                    centerCrop().
                    into(iv_two_code);
        }
    }

    @Override
    public void loadFaiBusinessCon(String errorMsg) {

    }

    CustomDialog savePicDialog;
    private void showSavePicDialog(final String picAddress){
        savePicDialog=new CustomDialog(this,
                R.style.Customdialog,
                "保存图片",
                "确定要将图片保存到手机吗？", new CustomDialog.ButtonListener() {
            @Override
            public void left() {
                //确定
                savePicDialog.dismiss();
                Target target=new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        Observable.OnSubscribe<String> observable= subscriber -> {
                            File imageDir=new File(FileUtils.imagePath);
                            boolean dirExist=true;
                            if(!imageDir.exists()){
                                dirExist=imageDir.mkdirs();
                            }
                            if(dirExist){
                                //图片名
                                SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmssSSS",
                                        Locale.CHINESE);
                                String picName=format.format(System.currentTimeMillis())+".jpg";
                                File file=new File(imageDir,picName);
                                boolean fileExist=false;
                                if(file.exists()){
                                    fileExist=!file.delete();//删除成功时为true
                                }
                                if(fileExist){
                                    subscriber.onError(new RuntimeException("创建文件失败"));
                                }else{
                                    if(bitmap!=null){
                                        BufferedOutputStream bos=null;
                                        try{
                                            bos=new BufferedOutputStream(new FileOutputStream(file),4*1024);
                                            if(bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos)){
                                                //二维码保存成功
                                                subscriber.onNext(file.getAbsolutePath());
                                            }else{
                                                //保存失败
                                                subscriber.onNext(null);
                                            }
                                            subscriber.onCompleted();
                                        }catch (Exception e){
                                            e.printStackTrace();
                                            subscriber.onError(e);
                                        }finally {
                                            if(bos!=null){
                                                try {
                                                    bos.close();
                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }
                                    }
                                }
                            }else{
                                subscriber.onError(new RuntimeException("创建文件夹失败"));
                            }
                        };
                        Observable.create(observable).
                                subscribeOn(Schedulers.io()).
                                observeOn(AndroidSchedulers.mainThread()).
                                subscribe(new Subscriber<String>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        closeLoadingDialog();
                                        ToastUtil.showShort("保存图片出错");
                                    }

                                    @Override
                                    public void onNext(String s) {
                                        closeLoadingDialog();
                                        if(TextUtils.isEmpty(s)){
                                            ToastUtil.showShort("保存图片失败");
                                        }else{
                                            try{
                                                File file=new File(s);
                                                //将二维码插入图库
                                                MediaStore.Images.Media.insertImage(getContentResolver(),
                                                        s,
                                                        file.getName(),
                                                        null);
                                                //发送广播，通知图库更新
                                                Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                                        Uri.fromFile(file));
                                                sendBroadcast(intent);
                                                ToastUtil.showShort("保存成功");
                                            }catch (FileNotFoundException e){
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {
                        ToastUtil.showShort("保存图片失败");
                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {
                        showLoadingDialog("请稍侯...");
                    }
                };
                Picasso.with(MyBusinessConActivity.this).load(picAddress).into(target);
            }

            @Override
            public void right() {
                //取消
                savePicDialog.dismiss();
            }
        },"确定","取消");
        savePicDialog.show();
    }
}
